package fr.emse.tatiana.filter;

import java.util.Vector;

import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;

import fr.emse.tatiana.TatianaConstants;

public class FilterAction {

	public static String rootpath = "";

	private String filtername;
	private Integer result;
	private Vector<Integer> paramids;

	public FilterAction(String filtername, Integer result, Vector<Integer> paramids) {
		this.filtername = filtername;
		this.result = result;
		this.paramids = paramids;
	}

	public void execute(FilterExecuter executer, boolean nocache) {
		Vector<String> params= new Vector<String>();
		String prehash = filtername;
		for (Integer id : paramids) {
			FilterParameter param = executer.getParameterAt(id);
			String paramvalue = param.getFilterableValue();
			params.add(paramvalue);
			prehash += paramvalue;
			prehash += param.getVersionNumber();
		}
		
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(TatianaConstants.TATIANA_PROJECT_NAME);

		IFile filterfile = project.getFolder(TatianaConstants.SCRIPTS_FOLDER_NAME).getFile(filtername+".xq");
		try {
			filterfile.refreshLocal(IResource.DEPTH_ZERO, null);
		} catch (CoreException e) {
			// never mind (maybe detect that filter exists)
		}
		prehash+=filterfile.getModificationStamp();
		IFile resultfile = project.getFolder(TatianaConstants.CACHE_FOLDER_NAME).getFile(prehash.hashCode()+".tat");
		String resultname = resultfile.getLocation().toString();
		String resultrelative = resultfile.getFullPath().makeRelative().toString();
		//System.err.println("Substring = "+value.substring(0, 1));
		// TODO z later see why some string don't have a / in front
		if( ! resultname.substring(0, 1).equals("/") ) {
			resultname = "/"+resultname;
		}
		System.err.println("prehash was "+ prehash);
		try {
			resultfile.refreshLocal(IResource.DEPTH_ZERO, null);
		} catch (CoreException e) {
			// never mind (maybe detect that filter exists)
		}
		if (!resultfile.exists() || nocache) {
			System.err.println("file does not exist:" + resultfile.getName());
			new XQueryOut(filterfile.getLocation().toString(),
					params.toArray(new String[]{}),
					resultname,
					ResourcesPlugin.getWorkspace().getRoot().getLocation().toString());

		} else {
			System.err.println("got file from cache:" + resultfile.getName());
		}
		executer.setVariableAt(result, new FilterParameter(result,"",resultrelative,FilterExecuter.ftype));
	}



}
